package com.hspedu.newData.dmsxl.回溯.棋盘问题;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-20 
 * @Version: 1.0
 */

// todo  检查一下问题
public class LC51N皇后 {

    List<List<String>> res = new ArrayList<>();
    public List<List<String>> solveNQueens(int n) {

        char[][] chessboard = new char[n][n];

        for (char[] c : chessboard) {
            Arrays.fill(c,'.');
        }
        backtracking(n,0,chessboard);
        return res;
    }

    public void backtracking(int n,int row,char[][] chessboard){
        if (row == n){
            res.add(Array2List(chessboard));
            return;
        }

        for (int col = 0; col < n; col++) {
            if (isValid(row,col,n,chessboard)){
                chessboard[row][col] = 'Q';
                backtracking(n,row+1,chessboard);
                chessboard[row][col] = '.';
            }
        }

    }

    public boolean isValid(int row,int col,int n,char[][] chessboard){

        // 列检查
        for (int i = 0; i < row; i++) {
            if (chessboard[i][col] == 'Q'){
                return false;
            }
        }

        // 45°检查
        for (int i = row-1,j=col-1; i >=0&&j>=0 ; i--,j--) {
            if (chessboard[i][j]=='Q'){
                return false;
            }
        }

        // 135°检查
        for (int i = row-1,j=col+1; i >=0&&j<=n-1 ; i--,j++) {
            if (chessboard[i][j]=='Q'){
                return false;
            }
        }

        return true;
    }

    public List Array2List(char[][] chessboard){
        List<String> list = new ArrayList<>();
        for (char[] chars : chessboard) {
            list.add(String.valueOf(chars));
        }
        return list;
    }
}
